package com.sx.manage.util;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;

import com.sx.cache.Cache;
import com.sx.common.util.DateUtil;
import com.sx.common.util.SquenceUtil;
import com.sx.common.util.http.constants.BasicAccountType;
import com.sx.common.util.http.model.PrimarykeyClass;
import com.sx.common.util.json.JackJsonUtil;
import com.sx.common.util.message.EMailMessageModel;
import com.sx.common.util.message.MessageForm;
import com.sx.common.util.message.MessageModel;
import com.sx.common.util.message.MessageType;
import com.sx.common.vo.BaseVO;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.manage.mybatis.form.BaseForm;

import net.sf.json.JSONObject;

/**
 * service impl 辅助类
 * 
 * @author lenovo
 *
 */
@SuppressWarnings({ "rawtypes"})
public class WebServiceUtil {
	// 系统日志添加
	private static Logger _log = LoggerFactory.getLogger(WebServiceUtil.class);
	private WebServiceUtil() {
	}
	/**
	 * 发送模版短信
	 * 
	 * @param phone
	 * @param tplId
	 *            短信模版ID
	 * @param tplValue
	 */
	public static BaseVO sendTplEmail(String email, String temail, String emialsub, String emialcontent, String userId, String url, MessageType messageType) {

		MessageModel message = get_emailMessage(email, temail, emialsub, emialcontent, userId, messageType);

		MessageForm messageForm = new MessageForm();
		messageForm.setMessagemodel(message);
		messageForm.setMessageTypes(new MessageType[] { messageType });
		_log.info("发送邮件: {}", JackJsonUtil.objToJson(messageForm));
		String result = HttpUtil.post(url, JackJsonUtil.objToJson(messageForm));
		_log.info(result);
		if (StringUtils.isBlank(result)) {
			return BaseVO.createErrorMsg("发送邮件返回为空");
		}
		JSONObject json = JSONObject.fromObject(result);
		boolean b = json.getBoolean("success");
		if (!b) {
			return BaseVO.createMsg(false, json.getString("code"), json.getString("msg"));
		}
		return BaseVO.createMsg(true, json.getString("code"), json.getString("msg"));
	}

	/**
	 * 邮件组件-组装EMailMessageModel
	 * 
	 * @param email
	 * @param temail
	 * @param emialsub
	 * @param emialcontent
	 * @param userId
	 * @param messageType
	 * @return
	 */
	public static MessageModel get_emailMessage(String email, String temail, String emialsub, String emialcontent, String userId, MessageType messageType) {
		EMailMessageModel eMailMessage = new EMailMessageModel();
		// 发送邮件地址
		eMailMessage.setEmail(email);
		// 接收方邮件地址
		eMailMessage.setTemail(temail);
		// 邮件主题
		eMailMessage.setEmialsub(emialsub);
		// 邮件正文
		eMailMessage.setEmialcontent(emialcontent);
		MessageModel message = new MessageModel();
		message.setUseid(userId);
		message.setEmailmessagemodel(eMailMessage);
		message.setMessagetype(messageType);
		return message;
	}

	/**
	 * 激活参数
	 * 
	 * @param emailCode
	 * @param values
	 * @return
	 */
	public static String formatValues(String emailCode, Object... values) {
		if (null == values || null == emailCode) {
			return null;
		}
		String text = null;
		text = String.format(emailCode, values);

		return text;
	}

	/*** 字段格式验证 ***/
	public static String fieldValidate(Validator validator, BaseForm form, BindingResult errors) {
		// 数据检验(第一种方式)
		validator.validate(form, errors);
		if (errors.hasErrors()) {
			String error = errorsMessage(errors);
			_log.error(error);
			return error;
		}
		return null;
	}

	/*** 错误信息提示处理 ***/
	public static String errorsMessage(org.springframework.validation.Errors errors) {
		if (errors.hasErrors() || errors.hasGlobalErrors()) {
			StringBuilder errInfo = new StringBuilder();
			List<FieldError> ferrors = errors.getFieldErrors();
			if ( !ferrors.isEmpty() ) {
				for (FieldError error : ferrors) {
					errInfo.append(error.getField() + ":" + error.getDefaultMessage() + ";");
					_log.error(error.getDefaultMessage());
				}
			}
			List<ObjectError> gerrors = errors.getGlobalErrors();
			if ( !gerrors.isEmpty()) {
				for (ObjectError error : gerrors) {
					errInfo.append(error.getDefaultMessage() + ";;");
				}
			}
			errors.reject(null, errInfo.toString());
			return errInfo.toString();
		}
		return "";
	}
	/** 生成支付中心摊位号
	public static String createAccountNo(Cache redisCache) {
		String dateStr = DateUtil.dateToStr(new Date(), "yyyyMM");
		String accountNo = SquenceUtil.makePrimarykey(PrimarykeyClass.SX_T_M_OPEN_ACCOUNT_HUAXIA2,"", redisCache);
		for(int i=0,l=(6-accountNo.length());i<l;i++) {
			accountNo="0"+accountNo;
		}
			   accountNo = 200+dateStr+accountNo;
		_log.info("新生成子账号accountNo={}",accountNo);
		return accountNo;
	}**/
	/** 生成华夏二期子账号**/
	public static String createBankAccountNo(Cache redisCache) {
		String dateStr = DateUtil.dateToStr(new Date(), "yyyyMM");
		String accountNo = SquenceUtil.makePrimarykey(PrimarykeyClass.SX_T_M_OPEN_ACCOUNT_HUAXIA2,"", redisCache);
		for(int i=0,l=(6-accountNo.length());i<l;i++) {
			accountNo="0"+accountNo;
		}
			   accountNo = 200+dateStr+accountNo;
		_log.info("新生成子账号accountNo={}",accountNo);
		return accountNo;
	}
	/**
	 * 摊位号生成
	 */
	public static String makeBasicAccountNo(BasicAccountType basicAccountType) {
		String accountNo = "";
		if (basicAccountType == null) {
			return accountNo;
		}
		if (basicAccountType.equals(BasicAccountType.COMPANY)) {
			accountNo = "c" + UUID.randomUUID().toString().replaceAll("-", "");
		} else if (basicAccountType.equals(BasicAccountType.PERSONAL)) {
			accountNo = "p" + UUID.randomUUID().toString().replaceAll("-", "");
		} else {
			accountNo = "b" + UUID.randomUUID().toString().replaceAll("-", "");
		}
		return accountNo;
	}
	/** 交易会员代码url**/
	public static String huaxia02TradeUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_TRADE_MEM_CODE;
	}
	/** 绑定出入金卡url**/
	public static String bindBankCardUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_BIND_BANK_CARD;
	}
	/** 绑定电子银行url**/
	public static String bindElecAccountUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_BIND_BANK_CARD;
	}
	/** 绑定出金卡url**/
	public static String bindBankOutCardUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_BIND_BANK_OUT_CARD;
	}
	/** 子账户信息变更url**/
	public static String accountInfoChangeUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_ACCOUNT_INFO_CHANGE;
	}
	/** 子账户状态变更url**/
	public static String accountStatusChangeUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_ACCOUNT_STATUS_CHANGE;
	}
	/** 子账户信息查询url**/
	public static String getAccountInfoUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_GET_ACCOUNT_INFO;
	}
	/** 子账户绑定信息查询url**/
	public static String getAccountBindInfoUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_GET_ACCOUNT_BIND_INFO;
	}
	/** 子账户余额**/
	public static String getAccountBalanceUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_ACCOUNT_BALANCE;
	}
	/** 账户签约信息查询**/
	public static String getContractAccountInfoUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_GET_CONTRACT_ACCOUNT;
	}
	/** 子账户交易记录查询**/
	public static String getTardeAdaptertTradeDetailUrl() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_TARDEADAPTER_TRADEDETAIL;
	}
	/** 获取支付单号**/
	public static String getPayCodeNo() {
		return null;//return MSystemConstants.ADAPETER_URL+MSystemConstants.HUAXIA02_GET_PAY_CODE_NO;
	}
	/** 判断银行是否为华夏银行**/
	public static boolean configHuaXiaBank(String cls_bank_name) {
		if(StringUtils.isBlank(cls_bank_name)) {
			_log.info("判断银行是否为华夏银行参数为空cls_bank_name={}",cls_bank_name);
			return false;
		}
		return cls_bank_name.contains("华夏");
	}
	
	/** 华夏银行直销银行开户**/
	public static String getDescOpenAccount() {
		return MSystemConstants.HUAXIADESC_URL+MSystemConstants.HUAXIADESC_OPEN_ACCOUNT_URL;
	}
}
